/**
 * FileName: HttpUtil
 * Author:   powersi
 * Date:     2020/12/31 16:56
 * Description: 播报
 */
package com.zm.demo.httpclient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Description: 播报
 * Author:      powersi
 * Date:        2020/12/31 16:56
 */
public class HttpUtil {
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    public static Map<String, Object> calc(String host, String startTime, String endTime, String incefaceName, String cookie) throws Exception {

        HashMap<String, Object> hashMap = new HashMap<>();
        String url = "http://"+ host +"/apiDispatch/v3?action=DescribeInovcationIndicators";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Cookie", cookie);
        StringEntity stringEntity = new StringEntity("{\"action\":\"DescribeInovcationIndicators\",\"serviceType\":\"tsf\",\"regionId\":1," +
                "\"data\":{\"dimension\":\"service\"," +
                "\"startTime\":\""+ startTime + "\"," +  //调整
                "\"endTime\":\""+ endTime +"\"," +    //调整参数
                "\"namespaceId\":\"namespace-gvkq5nvo\",\"callerServiceName\":\"\"," +
                "\"calleeServiceName\":\"hsa-fsi-nation\"," +
                "\"callerInterfaceName\":\"\"," +
                "\"calleeInterfaceName\":\""+ incefaceName +"\"," + //调整
                "\"Version\":\"2018-03-26\"}}", ContentType.APPLICATION_JSON);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        StringBuilder sb = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(httpEntity.getContent())); InputStream in1 = httpEntity.getContent()){
            String s;
            while ((s=in.readLine()) != null){
                sb.append(s);
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
//        String res = "{\"Response\":{\"RequestId\":\"7a43b059-b81b-4a16-b9a4-b6eae25c3501\",\"Result\":{\"InvocationQuantity\":null,\"InvocationSuccessRate\":null,\"InvocationAvgDuration\":null,\"InvocationQuantityDistribution\":[{\"CoordX\":\"1609459200000\",\"CoordY\":\"0.20\",\"CoordTag\":null},{\"CoordX\":\"1609460100000\",\"CoordY\":\"3.40\",\"CoordTag\":null},{\"CoordX\":\"1609460400000\",\"CoordY\":\"2.60\",\"CoordTag\":null},{\"CoordX\":\"1609460700000\",\"CoordY\":\"1.60\",\"CoordTag\":null},{\"CoordX\":\"1609461000000\",\"CoordY\":\"0.20\",\"CoordTag\":null},{\"CoordX\":\"1609462500000\",\"CoordY\":\"0.20\",\"CoordTag\":null},{\"CoordX\":\"1609462800000\",\"CoordY\":\"1.60\",\"CoordTag\":null},{\"CoordX\":\"1609463100000\",\"CoordY\":\"13.20\",\"CoordTag\":null},{\"CoordX\":\"1609463700000\",\"CoordY\":\"7.60\",\"CoordTag\":null},{\"CoordX\":\"1609464000000\",\"CoordY\":\"5.40\",\"CoordTag\":null},{\"CoordX\":\"1609464300000\",\"CoordY\":\"7.80\",\"CoordTag\":null},{\"CoordX\":\"1609464600000\",\"CoordY\":\"6.40\",\"CoordTag\":null},{\"CoordX\":\"1609464900000\",\"CoordY\":\"2.40\",\"CoordTag\":null},{\"CoordX\":\"1609465200000\",\"CoordY\":\"10.00\",\"CoordTag\":null},{\"CoordX\":\"1609465500000\",\"CoordY\":\"14.20\",\"CoordTag\":null},{\"CoordX\":\"1609465800000\",\"CoordY\":\"2.20\",\"CoordTag\":null},{\"CoordX\":\"1609466100000\",\"CoordY\":\"5.00\",\"CoordTag\":null},{\"CoordX\":\"1609466400000\",\"CoordY\":\"4.00\",\"CoordTag\":null},{\"CoordX\":\"1609466700000\",\"CoordY\":\"13.00\",\"CoordTag\":null}],\"InvocationSuccessDistribution\":[{\"CoordX\":\"1609459200000\",\"CoordY\":\"1\",\"CoordTag\":null},{\"CoordX\":\"1609460100000\",\"CoordY\":\"17\",\"CoordTag\":null},{\"CoordX\":\"1609460400000\",\"CoordY\":\"13\",\"CoordTag\":null},{\"CoordX\":\"1609460700000\",\"CoordY\":\"8\",\"CoordTag\":null},{\"CoordX\":\"1609461000000\",\"CoordY\":\"1\",\"CoordTag\":null},{\"CoordX\":\"1609462500000\",\"CoordY\":\"1\",\"CoordTag\":null},{\"CoordX\":\"1609462800000\",\"CoordY\":\"8\",\"CoordTag\":null},{\"CoordX\":\"1609463100000\",\"CoordY\":\"66\",\"CoordTag\":null},{\"CoordX\":\"1609463700000\",\"CoordY\":\"38\",\"CoordTag\":null},{\"CoordX\":\"1609464000000\",\"CoordY\":\"27\",\"CoordTag\":null},{\"CoordX\":\"1609464300000\",\"CoordY\":\"39\",\"CoordTag\":null},{\"CoordX\":\"1609464600000\",\"CoordY\":\"32\",\"CoordTag\":null},{\"CoordX\":\"1609464900000\",\"CoordY\":\"12\",\"CoordTag\":null},{\"CoordX\":\"1609465200000\",\"CoordY\":\"50\",\"CoordTag\":null},{\"CoordX\":\"1609465500000\",\"CoordY\":\"71\",\"CoordTag\":null},{\"CoordX\":\"1609465800000\",\"CoordY\":\"11\",\"CoordTag\":null},{\"CoordX\":\"1609466100000\",\"CoordY\":\"25\",\"CoordTag\":null},{\"CoordX\":\"1609466400000\",\"CoordY\":\"20\",\"CoordTag\":null},{\"CoordX\":\"1609466700000\",\"CoordY\":\"65\",\"CoordTag\":null}],\"InvocationFailedDistribution\":[{\"CoordX\":\"1609459200000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609460100000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609460400000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609460700000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609461000000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609462500000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609462800000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609463100000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609463700000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609464000000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609464300000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609464600000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609464900000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609465200000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609465500000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609465800000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609466100000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609466400000\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"1609466700000\",\"CoordY\":\"0\",\"CoordTag\":null}],\"InvocationStatusDistribution\":[{\"CoordX\":\"1xx\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"2xx\",\"CoordY\":\"505\",\"CoordTag\":null},{\"CoordX\":\"3xx\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"4xx\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"5xx\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"6xx\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"7xx\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"other\",\"CoordY\":\"0\",\"CoordTag\":null}],\"InvocationDurationDistribution\":[{\"CoordX\":\"0\",\"CoordY\":\"1\",\"CoordTag\":null},{\"CoordX\":\"50\",\"CoordY\":\"0\",\"CoordTag\":null},{\"CoordX\":\"100\",\"CoordY\":\"14\",\"CoordTag\":null},{\"CoordX\":\"200\",\"CoordY\":\"8\",\"CoordTag\":null},{\"CoordX\":\"300\",\"CoordY\":\"6\",\"CoordTag\":null},{\"CoordX\":\"400\",\"CoordY\":\"137\",\"CoordTag\":null},{\"CoordX\":\"800\",\"CoordY\":\"135\",\"CoordTag\":null},{\"CoordX\":\"1200\",\"CoordY\":\"100\",\"CoordTag\":null},{\"CoordX\":\"2000\",\"CoordY\":\"104\",\"CoordTag\":null}]}}}";
//        JSONObject jsonObject = JSONObject.parseObject(res);
        if (jsonObject == null || jsonObject.getJSONObject("Response") == null
                || jsonObject.getJSONObject("Response").getJSONObject("Result") == null){
            return hashMap;
        }

        //请求次数
        JSONArray invocationSuccessDistribution = jsonObject.getJSONObject("Response").getJSONObject("Result").getJSONArray("InvocationSuccessDistribution");
        AtomicInteger count = new AtomicInteger(0);
        invocationSuccessDistribution.forEach(j ->{
            JSONObject j1 = (JSONObject)j;
            Optional.of(j1.getInteger("CoordY")).ifPresent(v -> count.getAndAdd(j1.getInteger("CoordY")));
        });
        hashMap.put("count", count.get());
        //请求时间
        JSONArray InvocationDurationDistribution = jsonObject.getJSONObject("Response").getJSONObject("Result").getJSONArray("InvocationDurationDistribution");
//        AtomicLong duration = new AtomicLong(0);
        AtomicReference<BigDecimal> duration = new AtomicReference<>();
        duration.set(BigDecimal.ZERO);
        InvocationDurationDistribution.forEach(j ->{
            JSONObject j1 = (JSONObject)j;
            BigDecimal total = null;
            if (j1.getInteger("CoordX") == 2000){
                total = BigDecimal.valueOf(3000/100D).multiply(BigDecimal.valueOf(j1.getInteger("CoordY").longValue()));
            }else {
                total = BigDecimal.valueOf(j1.getInteger("CoordX")/100D).multiply(BigDecimal.valueOf(j1.getInteger("CoordY").longValue()));
            }
            duration.set(duration.get().add(total));
        });
        hashMap.put("duration", duration.get().divide(BigDecimal.valueOf(count.get()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100L)));
        return hashMap;
    }

    public static Map<String, Object> traces(String host, String startTime, String endTime, Map.Entry<String, String> entry, String cookie) throws Exception {
        log.info("traces start...");
        HashMap<String, Object> hashMap = new HashMap<>();
        String url = "http://"+ host +"/apiDispatch/v3?action=SearchTrace";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
        httpPost.addHeader("Cookie", cookie);

        Integer totalCount = 0;
        int offset = 0;
        JSONArray jsonArray = new JSONArray();
        int currentSize=0;
        do {
            StringEntity stringEntity = new StringEntity("{\n" +
                    "\t\"action\": \"SearchTrace\",\n" +
                    "\t\"serviceType\": \"tsf\",\n" +
                    "\t\"regionId\": 1,\n" +
                    "\t\"data\": {\n" +
                    "\t\t\"namespaceId\": \"namespace-gvkq5nvo\",\n" +
                    "\t\t\"errorTrace\": false,\n" +
                    "\t\t\"offset\": "+ offset +",\n" +
                    "\t\t\"limit\": 100,\n" +
                    "\t\t\"startTime\": \" "+ startTime + "\",\n" +
                    "\t\t\"endTime\": \""+ endTime +"\",\n" +
                    "\t\t\"calleeServiceName\": \"hsa-fsi-nation\",\n" +
                    "\t\t\"calleeInterfaceName\": \""+ entry.getKey() + "\",\n" +
                    "\t\t\"Version\": \"2018-03-26\"\n" +
                    "\t}\n" +
                    "}", ContentType.APPLICATION_JSON);
            offset += 100;
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            StringBuilder sb = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(httpEntity.getContent()))){
                String s;
                while ((s=in.readLine()) != null){
                    sb.append(s);
                }
            }
            JSONObject jsonObject = JSONObject.parseObject(sb.toString());
            JSONArray jsonArrayCurrent = null;
            if (jsonObject == null || jsonObject.getJSONObject("Response") == null
                    || jsonObject.getJSONObject("Response").getJSONObject("Result") == null
                    || (jsonArrayCurrent = jsonObject.getJSONObject("Response").getJSONObject("Result").getJSONArray("Content")) == null){
                return hashMap;
            }
            if (totalCount == 0){
                totalCount = jsonObject.getJSONObject("Response").getJSONObject("Result").getInteger("TotalCount");
            }
            currentSize += jsonArrayCurrent.size();
            jsonArray.addAll(jsonArrayCurrent);
        } while (currentSize < totalCount );

        //计算参数
        assembleTraceResult(hashMap, jsonArray, totalCount, entry.getValue());
        log.info("traces end...");
        return hashMap;
    }

    private static void assembleTraceResult(HashMap<String, Object> hashMap, JSONArray jsonArray, Integer totalCount, String intefaceName){
        {
            StringBuilder sb = new StringBuilder();
            hashMap.put("totalCount", totalCount);
            long successCount = jsonArray.stream().filter(j ->{
                JSONObject j1 = (JSONObject)j;
                return Objects.equals(j1.getString("ResultStatus"), "SUCCESS");
            }).count();

            BigDecimal successRate = BigDecimal.valueOf(successCount).multiply(BigDecimal.valueOf(100L)).divide(BigDecimal.valueOf(jsonArray.size()), 4, RoundingMode.HALF_UP);
            String successRateStr = String.format("%s%%", successRate);
            hashMap.put("successRate", successRate);
            if (successRate.compareTo(BigDecimal.valueOf(0.99D)) < 0){
                sb.append("请求低于阈值【99%】，请注意！");
            }

            int maxDuration = jsonArray.stream().map(j -> {
                JSONObject j1 = (JSONObject)j;
                return j1.getInteger("Duration");
            }).max((l1,l2) -> l1 > l2 ? 1 : -1).get();
            String maxDurationStr = BigDecimal.valueOf(maxDuration).divide(BigDecimal.valueOf(1000L), 2, RoundingMode.HALF_UP).toString();
            hashMap.put("maxDuration", maxDurationStr);
            if (maxDuration > 20*1000*1000){
                sb.append("最大请求时长超过阈值【20秒】，请注意！\n");
            }

            Long totalDuration = jsonArray.stream().map(j -> {
                JSONObject j1 = (JSONObject)j;
                return j1.getLong("Duration");
            }).reduce((l1,l2) -> l1 + l2 ).get();
            hashMap.put("totalDuration", totalDuration);

            BigDecimal avgDuration = BigDecimal.valueOf(totalDuration)
                    .divide(BigDecimal.valueOf(1000L), 4, RoundingMode.HALF_UP)
                    .divide(BigDecimal.valueOf(totalCount.longValue()), 2, RoundingMode.HALF_UP);
            String avgDurationStr = avgDuration.toString();
            hashMap.put("avgDuration", avgDurationStr);

            if (avgDuration.compareTo(BigDecimal.valueOf(3*1000)) > 0){
                sb.append("平均请求时长超过阈值【3秒】，请注意！");
            }

            if (sb.length() > 0){
                hashMap.put("alarm", true);
                hashMap.put("desc", String.format("接口: %s \n  统计次数: %s, 成功率=%s, 最大延时=%s毫秒, 平均响应时间=%s毫秒\n %s",
                        intefaceName, totalCount, successRateStr, maxDurationStr, avgDuration, sb.toString()));
            }else {
                hashMap.put("desc", String.format("接口: %s \n  统计次数: %s, 成功率=%s, 最大延时=%s毫秒, 平均响应时间=%s毫秒",
                        intefaceName, totalCount, successRateStr, maxDurationStr, avgDuration));
            }

        }
    }

    public static CookieCache login(String host) throws Exception {
        log.info("login start...");
        String url = "http://"+ host +"/accountDispatch/login";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
        StringEntity stringEntity = new StringEntity("{\n" +
                "\t\"opt\": \"login\",\n" +
                "\t\"accountName\": \"gdybj-cz-prd-c-sup\",\n" +
                "\t\"password\": \"QEVK0t7T+1LYv3qKRNBUwbOtSu2xZmRJjb/c5U4/t0E=\"\n" +
                "}", ContentType.APPLICATION_JSON);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        StringBuilder sb = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(httpEntity.getContent())); InputStream in1 = httpEntity.getContent()){
            String s;
            while ((s=in.readLine()) != null){
                sb.append(s);
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if (jsonObject == null
                || jsonObject.getJSONObject("Response") == null
                || jsonObject.getJSONObject("Response").getJSONObject("Result") == null
                ){
            log.info("login end...");
            return null;
        }

        if (jsonObject.getJSONObject("Response").getJSONObject("Result").getString("Token") == null
                || jsonObject.getJSONObject("Response").getJSONObject("Result").getString("Token").length() == 0){
            log.info("login end...");
            throw new Exception("Token为空！");
        }
        CookieCache cookieCache = new CookieCache();
        cookieCache.setCookie(jsonObject.getJSONObject("Response").getJSONObject("Result").getString("Token"));
        cookieCache.setLocalDateTime(LocalDateTime.now());
        log.info("login end...");
        return cookieCache;
    }


    public static CookieCache loginChitu(String host) throws Exception {
        log.info("loginChitu start...");
        String url = "http://"+ host +"/tdsqlpcloud/index.php/login/opt";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
        StringEntity stringEntity = new StringEntity("username=ylbzpt_sup_cz&password=Aa123456&verify_code=&actionxm=login", ContentType.APPLICATION_FORM_URLENCODED);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        StringBuilder sb = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(httpEntity.getContent())); InputStream in1 = httpEntity.getContent()){
            String s;
            while ((s=in.readLine()) != null){
                sb.append(s);
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if (jsonObject == null
                || jsonObject.getBoolean("success") == null
                || jsonObject.getBoolean("success") == false
                ){
            log.info("loginChitu end...");
            return null;
        }

        CookieCache cookieCache = new CookieCache();

        String session = response.getHeaders("Set-Cookie")[0].getElements()[0].toString();
        cookieCache.setCookie(session.substring(0, session.indexOf(";")));

        cookieCache.setLocalDateTime(LocalDateTime.now());
        log.info("loginChitu end...");
        return cookieCache;
    }


    /**
     * 查询数据库状态，数据盘大于90%，慢查询大于0，CPU大于80%，IO使用率大于 80%，数据盘使用率最大值/最小是>3，满足其中一个条件，进行预警
     * @return
     * @throws Exception
     */
    public static HashMap<String, Object> dbStatus(String host, Map.Entry<String, String> entry, String cookie) throws Exception{
        log.info("dbStatus start...");
        String url = "http://"+ host +"/tdsqlpcloud/index.php/instance/mysql/get?actionxm=search_mysql&cluster=tdsql_51883365";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
        httpPost.addHeader("Cookie", cookie);
        StringEntity stringEntity = new StringEntity("order=asc&limit=40&offset=0&fmdata%5Bmid%5D=&fmdata%5Bpmid%5D="+ entry.getKey() +"&fmdata%5Brstate%5D%5B%5D=0&fmdata%5Brstate%5D%5B%5D=1", ContentType.APPLICATION_FORM_URLENCODED);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        StringBuilder sb = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(httpEntity.getContent())); InputStream in1 = httpEntity.getContent()){
            String s;
            while ((s=in.readLine()) != null){
                sb.append(s);
            }
        }
        JSONArray jsonArray = JSONObject.parseArray(sb.toString());
        if (jsonArray == null){
            log.info("dbStatus end...");
            return null;
        }

        StringBuilder desc = new StringBuilder();
        //数据盘使用率，最大值，最大值和最小值倍数
        Double maxDataDirUsage = jsonArray.stream().map(json -> ((JSONObject)json).getDouble("data_dir_usage")).max((d1,d2) -> d1 > d2 ? 1 : -1).get();
        if (maxDataDirUsage > 80){
            desc.append(String.format("数据盘最大使用率【%s%%】，请注意！<br/>", maxDataDirUsage));
        }
        Double minDataDirUsage = jsonArray.stream().map(json -> ((JSONObject)json).getDouble("data_dir_usage")).min((d1,d2) -> d1 > d2 ? 1 : -1).get();
        BigDecimal divid = minDataDirUsage == 0L ? BigDecimal.ZERO : BigDecimal.valueOf(maxDataDirUsage).divide(BigDecimal.valueOf(minDataDirUsage), 2, RoundingMode.HALF_UP);
        if (divid.intValue() > 6){
            desc.append(String.format("数据盘使用率差异过大，最大使用率 / 最小使用率 = 【%s】，数据分布极度不合理，请注意！<br/>", divid.toString()));
        }

        //CPU使用率
        Double maxCPUUsage = jsonArray.stream().map(json -> ((JSONObject)json).getDouble("cpu_usage")).max((d1,d2) -> d1 > d2 ? 1 : -1).get();
        if (maxCPUUsage > 80){
            desc.append(String.format("CPU 最大使用率【%s%%】，请注意！<br/>", BigDecimal.valueOf(maxCPUUsage).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP).toString()));
        }

        //IO使用率
        Double maxIOUsage = jsonArray.stream().map(json -> ((JSONObject)json).getDouble("io_usage")).max((d1,d2) -> d1 > d2 ? 1 : -1).get();
        if (maxIOUsage > 80){
            desc.append(String.format("IO 最大使用率【%s%%】，请注意！<br/>", BigDecimal.valueOf(maxIOUsage).divide(BigDecimal.ONE, 2, RoundingMode.HALF_UP).toString()));
        }
        //慢SQL
        Integer slowSql = jsonArray.stream().map(json -> ((JSONObject)json).getInteger("slow_query")).reduce((d1,d2) -> d1 + d2).get();
        if (slowSql > 0){
            desc.append(String.format("存在慢SQL，慢SQL数 =【%s】，请注意！", slowSql));
        }
        log.info("dbStatus end...");
        HashMap<String, Object> hashMap = new HashMap<>();
        if (desc.length() > 0){
            hashMap.put("alarm", true);
            hashMap.put("desc", entry.getValue() + "<br/> " + desc.toString());
        }else {
            hashMap.put("desc", entry.getValue() + "<br/> " + "当前时间段正常");
        }
        return hashMap;
    }

    /**
     * 查询数据库状态，数据盘大于90%，慢查询大于0，CPU大于80%，IO使用率大于 80%，数据盘使用率最大值/最小是>3，满足其中一个条件，进行预警
     * @return
     * @throws Exception
     */
    public static HashMap<String, Object> slowSql(String host, String startTime, String endTime, Map.Entry<String, String> entry, String cookie) throws Exception{
        log.info("slowSql start...");
        String url = "http://"+ host +"/tdsqlpcloud/index.php/instance/log_slowquery/get?actionxm=search&cluster=tdsql_51883365";
//        String url = "http://19.15.76.101/tdsqlpcloud/index.php/instance/log_slowquery/get?actionxm=search&cluster=tdsql_51883365";
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
        httpPost.addHeader("Cookie", cookie);
//        StringEntity stringEntity = new StringEntity("sort=timestramp&order=desc&limit=100&offset=0&fmdata%5Bmid%5D=%2Ftdsqlzk%2Fgroup_1600835079_1576&fmdata%5Bpmid%5D=&fmdata%5Btime_begin%5D=2021-01-25+09%3A30&fmdata%5Btime_end%5D=2021-01-25+09%3A40&fmdata%5Badvance_where%5D=", ContentType.APPLICATION_FORM_URLENCODED);
        StringEntity stringEntity = new StringEntity("sort=timestramp&order=desc&limit=1000&offset=0&fmdata%5Bmid%5D="+entry.getKey()+"&fmdata%5Bpmid%5D="+ entry.getKey() +"&fmdata%5Btime_begin%5D="+ startTime +"&fmdata%5Btime_end%5D="+ endTime +"&fmdata%5Badvance_where%5D=", ContentType.APPLICATION_FORM_URLENCODED);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        StringBuilder sb = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(httpEntity.getContent())); InputStream in1 = httpEntity.getContent()){
            String s;
            while ((s=in.readLine()) != null){
                sb.append(s);
            }
        }
        JSONArray jsonArray = JSONObject.parseArray(sb.toString());
        if (jsonArray == null){
            log.info("slowSql end...");
            return null;
        }

        HashMap<String, Object> result = new HashMap<>();
        StringBuilder alarm = new StringBuilder();
        jsonArray.forEach((object) ->{
            JSONObject item = (JSONObject) object;
            if (item.getDouble("query_time_avg") > 10D || item.getDouble("lock_time_avg") > 10D){
                if (alarm.length() == 0){
                    alarm.append("<table border=\"1\" cellspacing=\"0\">")
                        .append(String.format("<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>",
                                "账号/客户端IP", "执行时间", "平均执行时间", "最大执行时间", "平均锁时间", "最大锁时间", "总发送行数", "平均扫描行数", "执行SQL"));
                }
                    alarm.append(String.format("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>"
                                        ,item.getString("user") + "<br/>" + item.getString("host")
                                        ,item.getString("timestramp")
                                        ,item.getString("query_time_avg")
                            ,item.getString("query_time_max")
                            ,item.getString("lock_time_avg")
                            ,item.getString("lock_time_max")
                            ,item.getString("rows_sent_sum")
                            ,item.getString("row_avg_sum")
                            ,item.getString("example_sql")
                    ));
            }
        });

        if (alarm.length() > 0){
            alarm.append("</table>");
            result.put("alarm", true);
            result.put("desc", entry.getValue() + "<br/> " + alarm.toString());
        }else {
            result.put("alarm", false);
        }
        log.info("slowSql end...");
        return result;
    }

    public static void main(String[] args) throws Exception {
        CookieCache cookieCache = loginChitu("19.15.76.101");
        Map<String,String> tdsqlInstance = new HashMap<>();
        tdsqlInstance.put("/tdsqlzk/group_1600835079_1576", "生产-结算中心-待遇管理-15067-group_1600835079_1576");
//        tdsqlInstance.put("/tdsqlzk/group_1597999212_278", "生产-异地就医业务库-15065-group_1597999212_278");
//        tdsqlInstance.put("/tdsqlzk/group_1600828525_1560", "生产-核心业务中台分布式数据库-15215-group_1600828525_1560");
//        tdsqlInstance.put("/tdsqlzk/group_1600160522_1546", "生产-医保业务基础子系统分布式数据库-15212-group_1600160522_1546");
//        tdsqlInstance.put("/tdsqlzk/group_1602554564_1630", "生产-病种分值数据库（分布式） 征缴中心-15133-group_1602554564_1630");

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now();
        String endTime = localDateTime.format(formatter);
        String startTime = localDateTime.plusMinutes(-100L).format(formatter);
//        dbStatus("19.15.76.101", tdsqlInstance.entrySet().iterator().next(), cookieCache.getCookie());
        slowSql("19.15.76.101", startTime, endTime, tdsqlInstance.entrySet().iterator().next(), "ci_session=3d301ca4972654a3b5e0bd8626bd25359a7c448e");
    }
}
